import type { Options } from 'intro.js/src/option'
import introJs from 'intro.js'
import 'intro.js/minified/introjs.min.css'
import './assets/introJs.css'
import { useSound } from '@vueuse/sound'
import type { FingerType } from '@/stores/finger'
import answerSfx from '@/assets/sound/correct_answer.mp3'

interface FingerOptions {
  // 每一步手指的对应id
  target: string
  // 每一步手指的对应类型
  type?: FingerType
  // 是否已反手显示
  isReverse?: boolean
  // 是否隐藏边框
  hideBorder?: boolean
  // 根据回调设置实际偏移
  posotionCallback: (rectInfo: DOMRect) => { x: number; y: number }
}

export const useIntro = (options: Partial<Options>, fingerOptions?: FingerOptions[]) => {
  const {
    fingerX,
    fingerY,
    type,
    isReverse,
  } = storeToRefs(useFinger())

  const fingerStore = useFinger()

  const { play } = useSound(answerSfx)

  const intro = introJs().setOptions({
    exitOnEsc: false,
    hidePrev: true,
    exitOnOverlayClick: false,
    showButtons: false,
    showBullets: false,
    ...options,
  }).onexit(() => {
    fingerStore.hideFinger()
  }).onafterchange(() => {

  }).onbeforechange(async (targetElement) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (fingerOptions) {
          const targetList = fingerOptions.map(i => i.target)
          if (targetList.includes(targetElement.id)) {
            const targetFingerOption = fingerOptions.filter(i => i.target === targetElement.id)[0]
            const targetRectInfo = targetElement.getBoundingClientRect()

            // 类型是点击外的其他动画，字段重设置
            if (targetFingerOption.type && targetFingerOption.type !== 'click')
              type.value = targetFingerOption.type
            else
              type.value = 'click'

            // 设置反手
            if (targetFingerOption.isReverse)
              isReverse.value = true

            else
              isReverse.value = false

            const finalPosition = targetFingerOption.posotionCallback(targetRectInfo)
            fingerX.value = finalPosition.x
            fingerY.value = finalPosition.y
          }
        }
        resolve(true)
      }, 400)
    })
  })

  function stop() {
    nextTick(() => {
      // 隐藏手势，关闭引导对话
      fingerStore.hideFinger()
      intro.exit(true)
    })
  }

  function start() {
    nextTick(() => {
      intro.start()
    })
  }

  function next() {
    playCorrect()
    intro.nextStep()
  }
  function playCorrect() {
    play()
  }

  onScopeDispose(() => {
    stop()
  })
  return {
    intro, stop, start, next, playCorrect,
  }
}
